/**
 * 修改密码
 */
import query from '../../untils/mysql';
import { Tip } from '../../untils/untils';
import { check, validationResult } from 'express-validator';

const validator = [
    check('oldPassword').notEmpty().withMessage("旧密码不能为空"),
    check('newPassword').notEmpty().withMessage("新密码不能为空").isLength({ min: 6, max: 16 }).withMessage('新密码长度6-16位之间'),
]
const POST = async (req: any, res: any, next: any) => {
    try {
        const { userId } = req.auth;
        const { oldPassword, newPassword } = req.body;
        var errors = validationResult(req);
        if (!errors.isEmpty()) {
            return Tip.tipError(res, errors.array()[0].msg);
        }

        if (oldPassword === newPassword) {
            return Tip.tipError(res, "新旧密码不能相同");
        }

        const userData = await query(`select * from user where id = '${userId}'`);
        if (userData.length === 0) {
            return Tip.tipError(res, "账号有误");
        }
        if (userData[0].password != oldPassword) {
            return Tip.tipError(res, "旧密码输入错误");
        }

        await query(`update user set password = '${newPassword}' where id = '${userId}'`);
        return Tip.tipSuccess(res, '修改成功')
    } catch (error: any) {
        Tip.tipError500(res, error)
    }
}

export {
    POST,
    validator
}